<?php
require_once __DIR__ . '/../../app/config/config.php';

$base_dir = __DIR__;
$deme_file = sprintf("%s/subscribe.demo", $base_dir);
$base_coins_dir = __DIR__ . "/Subscribe";
$cmds = ['start', 'stop', 'restart', 'reload', 'status', 'connections', 'clear', '-h'];
// 取CLI 传入参数
$cmd = isset($argv[1]) ? $argv[1] : 'start';
$params = isset($argv[2]) ? $argv[2] : '1min';
if ($cmd == '-h' || !in_array($cmd, $cmds)) {
    printf("Usage: php yourfile.php {start|stop|restart|reload|status|connections|clear}");
    exit();
}

if (!is_dir($base_coins_dir)) {
    mkdir($base_coins_dir, 0777, true);
}

$i = $sum = 0;
foreach (array_unique($CONIS_HASH) as $coin) {
    $sum++;
    $filename = sprintf("%s.%s",$coin, $params);
    $file_path = sprintf("%s/%s.php", $base_coins_dir, $filename);

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $file_path = str_replace(DIRECTORY_SEPARATOR, str_repeat(DIRECTORY_SEPARATOR, 2), $file_path);
    } else {
    }
    // 建立文件
    if (!file_exists($file_path) && $cmd != 'clear') {
        copy($deme_file, $file_path);
    }
    $message = 'error';

    switch ($cmd) {
        case 'start':
            // workerman 启动
            $command = sprintf("cd %s && php %s.php start -d ", $base_coins_dir, $filename);
            break;
        case 'stop':
            // workerman 停止
            $command = sprintf("cd %s && php %s.php stop ", $base_coins_dir, $filename);
            break;
        case 'restart':
            // workerman 重启
            $command = sprintf("cd %s && php %s.php restart ", $base_coins_dir, $filename);
            break;
        case 'reload':
            // workerman 平滑重启
            $command = sprintf("cd %s && php %s.php reload ", $base_coins_dir, $filename);
            break;
        case 'status':
            // workerman 查看状态
            $command = sprintf("cd %s && php %s.php status ", $base_coins_dir, $filename);
            break;
        case 'connections':
            // workerman 查看连接状态
            $command = sprintf("cd %s && php %s.php connections ", $base_coins_dir, $filename);
            break;
        case 'clear':
            // workerman 删除生成的文件
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                $command = sprintf("cd %s && del -y %s.php ", $base_coins_dir, $filename);
            } else {
                $command = sprintf("cd %s && rm -f %s.php ", $base_coins_dir, $filename);
            }

            break;
        default:
            continue;
            break;
    }
    // 异步启用后台处理进程
    if ($resource = popen($command, 'r')) {
//        while (!feof($resource)) {
//            $buffer = fgets($resource, 4096);
//            printf("%s\r\n", $buffer);
//        }
        pclose($resource);
        $message = 'ok';
        $i++;
    }

    printf("%s\t%s\t%s\r\n", $filename, $cmd, $message);

    usleep(mt_rand(20, 1000));
}

printf("command:%s\r\nsuccess:%d\tfailed:%d\ttotal:%d\r\n", $cmd, $i, ($sum - $i), $sum);
